package com.softserve.crazymachine.configurator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import javax.swing.JOptionPane;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XmlConverter {
/**
 * Writes settings into xml file
 * <p>
 * {@code void whriteToXml(Map<String,Object> map,String dir)}
 * @param map - HashMap object with settings
 * @param dir - directory + name of the config file
 */
	public static void whriteToXml(Map<String,Object> map,String dir){
		
		XStream xStream = new XStream(new DomDriver());
		xStream.alias("Server", Map.class);
		xStream.registerConverter(new CustomMapConverter());
		
		try{
			  
			  FileWriter fstream = new FileWriter(dir);
			  BufferedWriter out = new BufferedWriter(fstream);
			  out.write(xStream.toXML(map));
			  //Close the output stream
			  out.close();
			  }catch (Exception e){//Catch exception if any
				  JOptionPane.showMessageDialog(null, "Can't save server configurations.", "Error", JOptionPane.ERROR_MESSAGE);
			  }
	}
	/**
	 * Reads settings from xml file 
	 * <p>
	 * {@code Map<String,Object> readFromXml(String dir)}
	 * @param dir - directory of the config file
	 * @return HashMap object with data from config file
	 */
	public static Map<String,Object> readFromXml(String dir){
		Map<String,Object> map=null;
       BufferedReader bufferedReader = null;
        
        try {
            
            //Construct the BufferedReader object
            bufferedReader = new BufferedReader(new FileReader(dir));
            
            String line = null, xml="";
            
            while ((line = bufferedReader.readLine()) != null) {
                //Process the data, here we just print it out
                xml+=line+"\t";
            }
            XStream xStream = new XStream(new DomDriver());
			xStream.alias("Server", Map.class);
			xStream.registerConverter(new CustomMapConverter());
			map = (Map<String,Object>) xStream.fromXML(xml);
        } catch (FileNotFoundException ex) {
        	JOptionPane.showMessageDialog(null, "File"+dir+" not found.", "Error", JOptionPane.ERROR_MESSAGE);
        } catch (IOException ex) {
        	JOptionPane.showMessageDialog(null, "Can't read server configurations.", "Error", JOptionPane.ERROR_MESSAGE);
        } finally {
            //Close the BufferedReader
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
		 
		 return map;

	}

}